---
id: jwt
title: 14. JWTEncryption 静态类
sidebar_label: 14. JWTEncryption 静态类
---

## 14.1 生成 `Token`

```cs
// 读取配置信息生成 Token
var token = JWTEncryption.Encrypt(new Dictionary<string, object> { { "UserId", 1 }  });

// 配置 Token 过期时间
var token = JWTEncryption.Encrypt(new Dictionary<string, object> { { "UserId", 1 }  }, 20);

// 配置 Token 密钥
var token = JWTEncryption.Encrypt("monksoul@outlook.com", new Dictionary<string, object> { { "UserId", 1 }  });

// 配置算法
var token = JWTEncryption.Encrypt("monksoul@outlook.com", new Dictionary<string, object> { { "UserId", 1 }  }, SecurityAlgorithms.HmacSha256);
```

## 14.2 生成刷新 `Token`

```cs
var refreshToken = JWTEncryption.GenerateRefreshToken("token", 43200);
```

## 14.3 根据过期 `Token` 交换新 `Token`

```cs
var newToken = JWTEncryption.Exchange("过期 token", "与之匹配的刷新 token", [新的token过期时间], [容错值]);
```

## 14.4 授权处理程序自动刷新 `Token`

```cs
JWTEncryption.AutoRefreshToken(context, httpContext);
```

## 14.5 验证 `Token` 有效性

```cs
var (isVaild, tokenInfo) = JWTEncryption.Validate("token");
```

## 14.6 验证请求中 `Token` 有效性

```cs
var isValid = JWTEncryption.ValidateJwtBearerToken(httpContext, out tokenInfo);
```

## 14.7 读取 `Token` 信息（不含验证）

```cs
var tokenInfo = JWTEncryption.ReadJwtToken("token");
```
